package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.CartInfoService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSkuVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: atguigu
 * @create: 2025-05-07 15:51
 */
@Service
@Slf4j
public class CartInfoServiceImpl implements CartInfoService {


    @Autowired
    private RedisTemplate redisTemplate;//模版对象
    @Autowired
    private RemoteProductService remoteProductService;


    private String getCartKey(Long userId) {
        return "user:cart:" + userId;
    }

    /**
     * 将指定商品ID对应数量加入到购物车
     *
     * @param skuId
     * @param num
     */
    @Override
    public void addToCart(Long skuId, Integer num) {
        //1.获取当前登录的id
        Long userId = SecurityContextHolder.getUserId();
        //2.创建购物车结构key user:cart:用户id
        String cartKey = this.getCartKey(userId);
        String field = skuId.toString();
        //第一种写法
//        Boolean exists = redisTemplate.opsForHash().hasKey(cartKey, field);
        //第二种写法
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(cartKey);
        Boolean exists = boundHashOperations.hasKey(field);
        //3.判断购物车是否有商品
        //3.1如果存在 数量不能超过99
        if (exists) {
            CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(cartKey, field);
            Integer skuNum = cartInfo.getSkuNum();
            cartInfo.setSkuNum(skuNum + num > 99 ? 99 : skuNum + num);
            cartInfo.setUpdateTime(new Date());
//            redisTemplate.opsForHash().put(cartKey, field, cartInfo);
                boundHashOperations.put(field,cartInfo);
        } else {
            //如果商品不存在
            //3.2效验商品种类个数是否超过50
            Long size = redisTemplate.opsForHash().size(cartKey);
            if (size > 50) {
                throw new RuntimeException("添加种类数量超过50");
            }
            R<ProductSkuVo> r = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (r.getCode() != 200) {
                throw new ServiceException("远程服务调用失败" + r.getMsg());
            }
            ProductSkuVo data = r.getData();
//            System.out.println("data = " + data);
//            System.out.println("价格" + data.getSalePrice());
            //3.3创建购物车对象
            CartInfo cartInfo = new CartInfo();
            //属性赋值
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(data.getId());
            cartInfo.setCartPrice(data.getSalePrice());
            cartInfo.setSkuPrice(data.getSalePrice());
            cartInfo.setSkuNum(num > 99 ? 99 : num);
            cartInfo.setThumbImg(data.getThumbImg());
            cartInfo.setSkuName(data.getSkuName());
            cartInfo.setIsChecked(1);
            cartInfo.setCreateTime(new Date());
            //3.4将购物车数据写入Redis中
//            redisTemplate.opsForHash().put(cartKey, field, cartInfo);
            boundHashOperations.put(field,cartInfo);

        }
    }


    //查询购物车列表
    @Override
    public List<CartInfo> cartList() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = this.getCartKey(userId);
        List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cartKey);
        if (!CollectionUtils.isEmpty(cartInfoList)) {
            cartInfoList.stream()
                    //默认升序 值大小
                    //写法一 拿时间进行比较 降序
                    .sorted((o1,o2)->o2.getCreateTime().compareTo(o1.getCreateTime()))
                    //写法二按照时间进行降序排列 判断是否为空为空排到最后
//                    .sorted(Comparator.comparing(CartInfo::getCreateTime,
//                            Comparator.nullsLast(Comparator.reverseOrder())
//                    ))
                    .collect(Collectors.toList());
            return cartInfoList;

        }
        return new ArrayList<>();
    }

    //删除购物车
    @Override
    public void deleteCart(Long skuId) {
        //获取用户id
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        //获取缓存
        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        //
        hashOperations.delete(skuId.toString());

    }
    //更改状态
    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        //   1.获取用户id
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        //修改缓存
        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        //获取缓存
        //判断购物车里是否存在  存在获取
        if (hashOperations.hasKey(skuId.toString())) {
            CartInfo cartInfo = hashOperations.get(skuId.toString());
            //写入缓存 判读他给的状态是否异常
            if (isChecked != null) {
                cartInfo.setIsChecked(isChecked);
                //更新缓存
                hashOperations.put(skuId.toString(), cartInfo);
            }
        }

    }
    //修改商品全选状态
    @Override
    public void allCheckCart(Integer isChecked) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        BoundHashOperations<String, String, CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> values = boundHashOperations.values();
        values.forEach(value -> {
            Long skuId = value.getSkuId();
            value.setIsChecked(isChecked);
            boundHashOperations.put(skuId.toString(), value);
        });


    }

    //清空购物车
    @Override
    public void clearCart() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        redisTemplate.delete(cartKey);
    }

    @Override
    public List<CartInfo> getCartCheckedList() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCartKey(userId);
        List<CartInfo>cartCachInfoList= redisTemplate.opsForHash().values(cartKey);
        List<CartInfo> cartInfoList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(cartCachInfoList)){
            cartInfoList=cartCachInfoList
                    .stream()
                    //filter 过滤
                    .filter(item->item.getIsChecked().intValue()==1)
                    .collect(Collectors.toList());
        }
        return cartInfoList;
    }

}
